package com.lagou.sqlSession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperdStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.NameUtils;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;
import org.apache.commons.lang3.StringUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    private Connection connection;
    @Override
    public <T> List<T> query(Configuration configuration, MapperdStatement mapperdStatement, Object... params) throws Exception {
        // 1.注册驱动，获取连接
        connection = configuration.getDataSource().getConnection();

        // 2.获取并转换sql语句  selcet * from user where id = #{} and username = #{} -》 selcet * from user where id = ? and username = ?
            //转换过程中，还需要对#{}中的值进行解析和存储
            //之所以要设计成#{}这种占位符号，是为了解析传入的实体类型参数，获取javabean内对应的属性值
        String sql = mapperdStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        // 3.获取预处理对象，preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        // 4.设置参数
        Class<?> paramterClass = getClassType(mapperdStatement.getParamterType());
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            // 反射获取对应的字段
            Field declaredField = paramterClass.getDeclaredField(content);
            // 暴力访问
            declaredField.setAccessible(true);
            Object paramsValue = declaredField.get(params[0]);
            //设置参数
            preparedStatement.setObject(i+1, paramsValue);
        }
        // 5.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        // 6.封装返回结果集
        Class<?> resultClass = getClassType(mapperdStatement.getResultType());
        Method[] methods = resultClass.getMethods();
        ArrayList<Object> resutlList = new ArrayList<>();
        while (resultSet.next()) {
            //获取数据库表的元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object resultObject = resultClass.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段值
                Object columnValue = resultSet.getObject(columnName);
                // 使用反射或者内省，根据数据库表和实体的对应关系，完成封装， 自动将下划线的字段名转为驼峰命名
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(NameUtils.getHumnName(columnName), resultClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(resultObject, columnValue);
            }
            resutlList.add(resultObject);
        }
        close();
        return (List<T>) resutlList;
    }

    @Override
    public int doUpdate(Configuration configuration, MapperdStatement mapperdStatement, Object... params) throws Exception {
        // 1.注册驱动，获取连接
        connection = configuration.getDataSource().getConnection();

        // 2.获取并转换sql语句  selcet * from user where id = #{} and username = #{} -》 selcet * from user where id = ? and username = ?
        //转换过程中，还需要对#{}中的值进行解析和存储
        //之所以要设计成#{}这种占位符号，是为了解析传入的实体类型参数，获取javabean内对应的属性值
        String sql = mapperdStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        // 3.获取预处理对象，preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        // 4.设置参数
        Class<?> paramterClass = getClassType(mapperdStatement.getParamterType());
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            // 反射获取对应的字段
            Field declaredField = paramterClass.getDeclaredField(content);
            // 暴力访问
            declaredField.setAccessible(true);
            Object paramsValue = declaredField.get(params[0]);
            //设置参数
            preparedStatement.setObject(i+1, paramsValue);
        }
        // 5.执行sql
        int row = preparedStatement.executeUpdate();
        close();
        return row;
    }


    @Override
    public void close() throws SQLException {
        connection.close();
    }

    /**
     * 获取类对象
     * @param paramterType
     * @return
     * @throws ClassNotFoundException
     */
    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if (StringUtils.isNotBlank(paramterType)) {
            Class<?> aClass = Class.forName(paramterType);
            return aClass;
        }
        return null;
    }

    /**
     *  完成对#{}的解析工作
     *  1. 将#{} 用 ? 代替
     *  2. 解析出#{}里面的值，进行存储
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        // 标记处理类：配置标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();

        // 解析类
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的sql
        String sqlTest = genericTokenParser.parse(sql);
        //解析醋回来的参数名list
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        return new BoundSql(sqlTest, parameterMappings);
    }
}
